<template xmlns="http://www.w3.org/1999/html">
  <div>
    <div><input type="button" value="全选" @click="selectAll"></div>
    <div><input type="button" value="取消全选" @click="unSelectAll"></div>
    <div>
      <li v-for="city in cityList" :key="city.value">
        <input type="checkbox" name="city" :value="city.value"  @change="select(city)" :checked="city.flag">{{city.name}}
      </li>
    </div>
  </div>
</template>

<script>
export default {
  name: "CheckBox",
  data() {
    return {
      cityList: [
        {name:'南京',value:'nanjing',flag: false},
        {name:'北京',value:'beijing',flag: false},
        {name:'上海',value:'shanghai',flag: false},
        {name:'呼和浩特',value:'huhehaote',flag: false},
        {name:'衡水',value:'hengshui',flag: false}
      ],
      citySelect:[]
    }
  },
  methods: {
    // 选择事件
    select(city){
      console.log('选择事件前',city.flag)
      city.flag = !city.flag;
      this.citySelect = []
      for (let i = 0; i < this.cityList.length; i++){
        if(this.cityList[i].flag){
          this.citySelect.push(this.cityList[i])
        }
      }
      this.$emit("update:citySel",this.citySelect)
      console.log('选择事件后',city.flag)
    },
    selectAll() { // 全选
      this.citySelect = []
      for (let i = 0; i < this.cityList.length; i++){
        this.cityList[i].flag = true
        this.citySelect.push(this.cityList[i])
      }
      this.$emit("update:citySel",this.citySelect)
    },
    unSelectAll() {// 取消全选
      for (let i = 0; i < this.cityList.length; i++){
        this.cityList[i].flag = false
      }
      this.$emit("update:citySel",[])
    }
  }
}
</script>

<style scoped>

</style>
